<template>
  <div class="performance-trend-container">
    <div class="page-header">
      <h1>📈 系统性能趋势分析</h1>
      <p class="page-subtitle">实时监控系统性能，智能预测宕机风险</p>
    </div>

    <div class="control-panel">
      <div class="control-section">
        <label class="control-label">📡 选择主机</label>
        <div class="host-selector">
          <label v-for="host in availableHosts" :key="host.id"
                 :class="['host-chip', { 'selected': selectedHostIds.includes(host.id) }]">
            <input type="checkbox" :value="host.id" v-model="selectedHostIds"
                   @change="onHostSelectionChange" class="host-checkbox">
            <span class="chip-content">
              <span class="chip-name">{{ host.name }}</span>
              <span class="chip-ip">{{ host.ip }}</span>
            </span>
          </label>
        </div>
      </div>

      <div class="control-section">
        <label class="control-label">⏰ 分析时段</label>
        <div class="time-range-selector">
          <button v-for="range in timeRanges" :key="range.value"
                  :class="['time-btn', { 'active': timeRange === range.value }]"
                  @click="selectTimeRange(range.value)">
            {{ range.label }}
          </button>
        </div>
      </div>

      <div class="control-section">
        <label class="control-label">📊 监控指标</label>
        <div class="metric-selector">
          <label v-for="metric in metrics" :key="metric.value"
                 :class="['metric-chip', { 'selected': selectedMetrics.includes(metric.value) }]">
            <input type="checkbox" :value="metric.value" v-model="selectedMetrics"
                   @change="onMetricChange" class="metric-checkbox">
            <span class="metric-icon">{{ metric.icon }}</span>
            <span class="metric-label">{{ metric.label }}</span>
          </label>
        </div>
      </div>

      <div class="control-section">
        <button @click="refreshData" class="action-btn refresh-btn" :disabled="isLoading">
          <span v-if="isLoading">🔄 刷新中...</span>
          <span v-else>🔄 刷新数据</span>
        </button>
        <button @click="enableAutoRefresh = !enableAutoRefresh" 
                :class="['action-btn', 'auto-refresh-btn', { 'active': enableAutoRefresh }]">
          <span>{{ enableAutoRefresh ? '⏸️ 停止自动刷新' : '▶️ 自动刷新' }}</span>
        </button>
      </div>
    </div>

    <div class="charts-container">
      <div v-if="selectedMetrics.includes('cpu')" class="chart-card">
        <div class="chart-header">
          <h3>🖥️ CPU使用率趋势</h3>
          <span class="last-update">最后更新: {{ lastUpdateTime }}</span>
        </div>
        <div ref="cpuChartRef" class="chart-content"></div>
        <div class="prediction-panel">
          <h4>🔮 性能预测</h4>
          <div class="prediction-cards">
            <div class="prediction-card" v-for="pred in cpuPredictions" :key="pred.host">
              <span class="pred-host">{{ pred.hostName }}</span>
              <span :class="['pred-value', pred.riskLevel]">{{ pred.predicted }}%</span>
              <span class="pred-label">{{ pred.label }}</span>
            </div>
          </div>
        </div>
      </div>

      <div v-if="selectedMetrics.includes('memory')" class="chart-card">
        <div class="chart-header">
          <h3>💾 内存使用率趋势</h3>
          <span class="last-update">最后更新: {{ lastUpdateTime }}</span>
        </div>
        <div ref="memoryChartRef" class="chart-content"></div>
        <div class="prediction-panel">
          <h4>🔮 性能预测</h4>
          <div class="prediction-cards">
            <div class="prediction-card" v-for="pred in memoryPredictions" :key="pred.host">
              <span class="pred-host">{{ pred.hostName }}</span>
              <span :class="['pred-value', pred.riskLevel]">{{ pred.predicted }}%</span>
              <span class="pred-label">{{ pred.label }}</span>
            </div>
          </div>
        </div>
      </div>

      <div v-if="selectedMetrics.includes('disk')" class="chart-card">
        <div class="chart-header">
          <h3>💿 磁盘使用率趋势</h3>
          <span class="last-update">最后更新: {{ lastUpdateTime }}</span>
        </div>
        <div ref="diskChartRef" class="chart-content"></div>
        <div class="prediction-panel">
          <h4>🔮 性能预测</h4>
          <div class="prediction-cards">
            <div class="prediction-card" v-for="pred in diskPredictions" :key="pred.host">
              <span class="pred-host">{{ pred.hostName }}</span>
              <span :class="['pred-value', pred.riskLevel]">{{ pred.predicted }}%</span>
              <span class="pred-label">{{ pred.label }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div v-if="riskAlerts.length > 0" class="risk-alerts">
      <h3>⚠️ 风险告警</h3>
      <div class="alert-list">
        <div v-for="(alert, index) in riskAlerts" :key="index" :class="['alert-item', alert.level]">
          <span class="alert-icon">{{ alert.icon }}</span>
          <div class="alert-content">
            <div class="alert-title">{{ alert.title }}</div>
            <div class="alert-message">{{ alert.message }}</div>
          </div>
          <span class="alert-time">{{ alert.time }}</span>
        </div>
      </div>
    </div>

    <div v-if="selectedHostIds.length === 0" class="empty-state">
      <div class="empty-icon">📊</div>
      <div class="empty-text">请选择要监控的主机</div>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import api from '../services/api'

const availableHosts = ref([])
const selectedHostIds = ref([])
const timeRange = ref(6)
const selectedMetrics = ref(['cpu', 'memory', 'disk'])
const isLoading = ref(false)
const enableAutoRefresh = ref(false)
const lastUpdateTime = ref('-')

const cpuChartRef = ref(null)
const memoryChartRef = ref(null)
const diskChartRef = ref(null)
let cpuChart = null
let memoryChart = null
let diskChart = null

const performanceData = ref({ cpu: {}, memory: {}, disk: {} })
const cpuPredictions = ref([])
const memoryPredictions = ref([])
const diskPredictions = ref([])
const riskAlerts = ref([])

const timeRanges = [
  { label: '6小时', value: 6 },
  { label: '12小时', value: 12 },
  { label: '24小时', value: 24 }
]

const metrics = [
  { label: 'CPU', value: 'cpu', icon: '🖥️' },
  { label: '内存', value: 'memory', icon: '💾' },
  { label: '磁盘', value: 'disk', icon: '💿' }
]

const hostColors = ['#ff6b6b', '#4ecdc4', '#45b7d1', '#ffa94d', '#a8e6cf', '#dda15e', '#bc6c25', '#9b59b6']
let refreshTimer = null

const fetchHosts = async () => {
  try {
    const response = await api.getHosts()
    availableHosts.value = response.results || response
    if (availableHosts.value.length > 0) {
      selectedHostIds.value = availableHosts.value.slice(0, Math.min(3, availableHosts.value.length)).map(h => h.id)
    }
  } catch (error) {
    console.error('获取主机列表失败:', error)
  }
}

const generateMockData = (hostId, hours) => {
  const now = Date.now()
  const interval = 5 * 60 * 1000
  const points = (hours * 60) / 5
  const data = []
  let baseValue = 20 + Math.random() * 30
  
  for (let i = 0; i < points; i++) {
    const timestamp = now - (points - i) * interval
    const trend = Math.sin(i / points * Math.PI) * 15
    const noise = (Math.random() - 0.5) * 10
    let value = baseValue + trend + noise
    if (Math.random() > 0.95) value += Math.random() * 20
    value = Math.max(0, Math.min(100, value))
    data.push({ time: timestamp, value: value })
  }
  return data
}

const predictValue = (data, futurePoints = 12) => {
  if (data.length < 2) return data[data.length - 1]?.value || 0
  
  // 使用最近20个数据点进行预测
  const recentData = data.slice(-20)
  const n = recentData.length
  
  // 线性回归计算
  let sumX = 0, sumY = 0, sumXY = 0, sumX2 = 0
  recentData.forEach((point, index) => {
    sumX += index
    sumY += point.value
    sumXY += index * point.value
    sumX2 += index * index
  })
  
  const slope = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX)
  const intercept = (sumY - slope * sumX) / n
  const predicted = slope * (n + futurePoints) + intercept
  
  // 限制在0-100范围内，但如果预测值>100，返回99.9表示即将爆满
  if (predicted > 100) return 99.9
  return Math.max(0, Math.min(100, predicted))
}

const assessRisk = (predicted) => {
  // 调整风险阈值，更合理地评估风险
  if (predicted >= 95) return { level: 'critical', label: '严重风险' }
  if (predicted >= 85) return { level: 'high', label: '高风险' }
  if (predicted >= 75) return { level: 'medium', label: '中等风险' }
  if (predicted >= 60) return { level: 'warning', label: '需要关注' }
  return { level: 'low', label: '正常' }
}

const refreshData = async () => {
  if (selectedHostIds.value.length === 0) return
  isLoading.value = true
  try {
    // 使用真实API获取巡检历史数据
    const hours = timeRange.value
    
    // 清空旧数据
    performanceData.value.cpu = {}
    performanceData.value.memory = {}
    performanceData.value.disk = {}
    
    // 为每个选中的主机获取数据
    for (const hostId of selectedHostIds.value) {
      try {
        const response = await api.getInspectionChartData(hostId, hours)
        
        if (response.timestamps && response.timestamps.length > 0) {
          // 将API数据转换为图表需要的格式
          performanceData.value.cpu[hostId] = response.timestamps.map((time, index) => ({
            time: time,
            value: response.cpu[index]
          }))
          
          performanceData.value.memory[hostId] = response.timestamps.map((time, index) => ({
            time: time,
            value: response.memory[index]
          }))
          
          performanceData.value.disk[hostId] = response.timestamps.map((time, index) => ({
            time: time,
            value: response.disk[index]
          }))
        } else {
          // 如果没有历史数据，使用模拟数据
          performanceData.value.cpu[hostId] = generateMockData(hostId, timeRange.value)
          performanceData.value.memory[hostId] = generateMockData(hostId, timeRange.value)
          performanceData.value.disk[hostId] = generateMockData(hostId, timeRange.value)
        }
      } catch (error) {
        console.error(`获取主机${hostId}数据失败:`, error)
        // 失败时使用模拟数据
        performanceData.value.cpu[hostId] = generateMockData(hostId, timeRange.value)
        performanceData.value.memory[hostId] = generateMockData(hostId, timeRange.value)
        performanceData.value.disk[hostId] = generateMockData(hostId, timeRange.value)
      }
    }
    
    calculatePredictions()
    await nextTick()
    updateCharts()
    generateRiskAlerts()
    lastUpdateTime.value = new Date().toLocaleTimeString('zh-CN')
  } catch (error) {
    console.error('刷新数据失败:', error)
  } finally {
    isLoading.value = false
  }
}

const calculatePredictions = () => {
  cpuPredictions.value = []
  memoryPredictions.value = []
  diskPredictions.value = []
  selectedHostIds.value.forEach(hostId => {
    const host = availableHosts.value.find(h => h.id === hostId)
    if (!host) return
    const cpuPredicted = predictValue(performanceData.value.cpu[hostId] || [], timeRange.value)
    const cpuRisk = assessRisk(cpuPredicted)
    cpuPredictions.value.push({ host: hostId, hostName: host.name, predicted: cpuPredicted.toFixed(1), riskLevel: cpuRisk.level, label: cpuRisk.label })
    const memPredicted = predictValue(performanceData.value.memory[hostId] || [], timeRange.value)
    const memRisk = assessRisk(memPredicted)
    memoryPredictions.value.push({ host: hostId, hostName: host.name, predicted: memPredicted.toFixed(1), riskLevel: memRisk.level, label: memRisk.label })
    const diskPredicted = predictValue(performanceData.value.disk[hostId] || [], timeRange.value)
    const diskRisk = assessRisk(diskPredicted)
    diskPredictions.value.push({ host: hostId, hostName: host.name, predicted: diskPredicted.toFixed(1), riskLevel: diskRisk.level, label: diskRisk.label })
  })
}

const generateRiskAlerts = () => {
  riskAlerts.value = []
  cpuPredictions.value.forEach(pred => {
    if (pred.riskLevel === 'critical' || pred.riskLevel === 'high') {
      riskAlerts.value.push({ level: pred.riskLevel, icon: '🖥️', title: `${pred.hostName} CPU风险`, message: `预测CPU使用率将达到 ${pred.predicted}%，建议及时处理`, time: new Date().toLocaleTimeString('zh-CN') })
    }
  })
  memoryPredictions.value.forEach(pred => {
    if (pred.riskLevel === 'critical' || pred.riskLevel === 'high') {
      riskAlerts.value.push({ level: pred.riskLevel, icon: '💾', title: `${pred.hostName} 内存风险`, message: `预测内存使用率将达到 ${pred.predicted}%，建议增加内存`, time: new Date().toLocaleTimeString('zh-CN') })
    }
  })
  diskPredictions.value.forEach(pred => {
    if (pred.riskLevel === 'critical' || pred.riskLevel === 'high') {
      riskAlerts.value.push({ level: pred.riskLevel, icon: '💿', title: `${pred.hostName} 磁盘风险`, message: `预测磁盘使用率将达到 ${pred.predicted}%，建议清理空间`, time: new Date().toLocaleTimeString('zh-CN') })
    }
  })
}

const initCharts = () => {
  if (cpuChartRef.value && !cpuChart) cpuChart = echarts.init(cpuChartRef.value)
  if (memoryChartRef.value && !memoryChart) memoryChart = echarts.init(memoryChartRef.value)
  if (diskChartRef.value && !diskChart) diskChart = echarts.init(diskChartRef.value)
}

const updateCharts = () => {
  initCharts()
  if (selectedMetrics.value.includes('cpu') && cpuChart) updateChart(cpuChart, performanceData.value.cpu, 'CPU使用率 (%)')
  if (selectedMetrics.value.includes('memory') && memoryChart) updateChart(memoryChart, performanceData.value.memory, '内存使用率 (%)')
  if (selectedMetrics.value.includes('disk') && diskChart) updateChart(diskChart, performanceData.value.disk, '磁盘使用率 (%)')
}

const updateChart = (chart, data, yAxisName) => {
  const series = []
  selectedHostIds.value.forEach((hostId, index) => {
    const host = availableHosts.value.find(h => h.id === hostId)
    if (!host || !data[hostId]) return
    series.push({
      name: host.name, type: 'line', smooth: true, symbol: 'circle', symbolSize: 6,
      lineStyle: { width: 3 }, itemStyle: { color: hostColors[index % hostColors.length] },
      data: data[hostId].map(point => [point.time, point.value.toFixed(2)]),
      markLine: { silent: true, lineStyle: { color: '#ff6b6b', type: 'dashed' }, data: [{ yAxis: 80, label: { formatter: '告警线 (80%)' } }] }
    })
  })
  chart.setOption({
    tooltip: { trigger: 'axis', axisPointer: { type: 'cross' } },
    legend: { data: series.map(s => s.name), top: 10 },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: { type: 'time', boundaryGap: false },
    yAxis: { type: 'value', name: yAxisName, min: 0, max: 100 },
    series: series
  })
}

const selectTimeRange = (range) => { timeRange.value = range; refreshData() }
const onHostSelectionChange = () => refreshData()
const onMetricChange = async () => { await nextTick(); initCharts(); updateCharts() }

watch(enableAutoRefresh, (enabled) => {
  if (enabled) refreshTimer = setInterval(() => refreshData(), 30000)
  else if (refreshTimer) { clearInterval(refreshTimer); refreshTimer = null }
})

onMounted(async () => {
  await fetchHosts()
  await refreshData()
  window.addEventListener('resize', () => { cpuChart?.resize(); memoryChart?.resize(); diskChart?.resize() })
})

onUnmounted(() => {
  if (refreshTimer) clearInterval(refreshTimer)
  cpuChart?.dispose(); memoryChart?.dispose(); diskChart?.dispose()
})
</script>

<style scoped>
.performance-trend-container { padding: 20px; max-width: 1800px; margin: 0 auto; }
.page-header { text-align: center; margin-bottom: 30px; }
.page-header h1 { font-size: 32px; color: var(--color-accent-pink); margin: 0 0 10px 0; font-weight: 700; }
.page-subtitle { color: var(--color-text-secondary); font-size: 14px; margin: 0; }
.control-panel { background: var(--color-bg-secondary); border-radius: 20px; padding: 25px; margin-bottom: 25px; box-shadow: var(--shadow-card); }
.control-section { margin-bottom: 20px; }
.control-section:last-child { margin-bottom: 0; }
.control-label { display: block; font-size: 14px; font-weight: 600; color: var(--color-text-primary); margin-bottom: 12px; }
.host-selector, .time-range-selector, .metric-selector { display: flex; flex-wrap: wrap; gap: 10px; }
.host-chip, .metric-chip { display: flex; align-items: center; gap: 8px; padding: 10px 15px; background: var(--color-bg-primary); border: 2px solid var(--color-border); border-radius: 12px; cursor: pointer; transition: all 0.3s; }
.host-chip:hover, .metric-chip:hover { border-color: var(--color-accent-pink); transform: translateY(-2px); }
.host-chip.selected, .metric-chip.selected { background: var(--color-bg-tertiary); border-color: var(--color-accent-pink); }
.host-checkbox, .metric-checkbox { width: 18px; height: 18px; cursor: pointer; accent-color: var(--color-accent-pink); }
.chip-content { display: flex; flex-direction: column; gap: 2px; }
.chip-name { color: var(--color-text-primary); font-size: 13px; font-weight: 600; }
.chip-ip { color: var(--color-text-secondary); font-size: 11px; font-family: monospace; }
.time-btn { padding: 10px 20px; background: var(--color-bg-primary); border: 2px solid var(--color-border); border-radius: 12px; color: var(--color-text-primary); font-size: 14px; font-weight: 600; cursor: pointer; transition: all 0.3s; }
.time-btn:hover { border-color: var(--color-accent-pink); transform: translateY(-2px); }
.time-btn.active { background: linear-gradient(135deg, var(--color-accent-pink), var(--color-accent-purple)); border-color: transparent; color: white; }
.metric-icon { font-size: 18px; }
.metric-label { color: var(--color-text-primary); font-size: 14px; font-weight: 600; }
.action-btn { padding: 12px 24px; border: none; border-radius: 12px; font-size: 14px; font-weight: 600; cursor: pointer; transition: all 0.3s; margin-right: 10px; }
.refresh-btn { background: linear-gradient(135deg, var(--color-accent-success), #4caf50); color: white; }
.refresh-btn:hover:not(:disabled) { transform: translateY(-2px); box-shadow: var(--shadow-hover); }
.refresh-btn:disabled { opacity: 0.6; cursor: not-allowed; }
.auto-refresh-btn { background: var(--color-bg-primary); border: 2px solid var(--color-border); color: var(--color-text-primary); }
.auto-refresh-btn.active { background: linear-gradient(135deg, var(--color-accent-pink), var(--color-accent-purple)); border-color: transparent; color: white; }
.charts-container { display: flex; flex-direction: column; gap: 25px; }
.chart-card { background: var(--color-bg-secondary); border-radius: 20px; padding: 25px; box-shadow: var(--shadow-card); border: 2px solid var(--color-border); }
.chart-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; padding-bottom: 15px; border-bottom: 2px solid var(--color-border); }
.chart-header h3 { font-size: 20px; color: var(--color-text-primary); margin: 0; font-weight: 700; }
.last-update { color: var(--color-text-secondary); font-size: 13px; }
.chart-content { height: 400px; margin-bottom: 20px; }
.prediction-panel { background: var(--color-bg-primary); border-radius: 15px; padding: 20px; }
.prediction-panel h4 { font-size: 16px; color: var(--color-text-primary); margin: 0 0 15px 0; font-weight: 700; }
.prediction-cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; }
.prediction-card { display: flex; flex-direction: column; gap: 5px; padding: 15px; background: var(--color-bg-secondary); border: 2px solid var(--color-border); border-radius: 12px; text-align: center; }
.pred-host { font-size: 13px; color: var(--color-text-secondary); font-weight: 600; }
.pred-value { font-size: 24px; font-weight: 700; }
.pred-value.low { color: var(--color-accent-success); }
.pred-value.warning { color: #ffa94d; }
.pred-value.medium { color: var(--color-accent-orange); }
.pred-value.high { color: #ff6b6b; }
.pred-value.critical { color: #f44336; }
.pred-label { font-size: 12px; color: var(--color-text-secondary); }
.risk-alerts { background: var(--color-bg-secondary); border-radius: 20px; padding: 25px; margin-top: 25px; box-shadow: var(--shadow-card); border: 2px solid #ff6b6b; }
.risk-alerts h3 { font-size: 20px; color: #ff6b6b; margin: 0 0 20px 0; font-weight: 700; }
.alert-list { display: flex; flex-direction: column; gap: 15px; }
.alert-item { display: flex; align-items: center; gap: 15px; padding: 15px; border-radius: 12px; border: 2px solid; }
.alert-item.high { background: rgba(255, 152, 0, 0.1); border-color: #ff9800; }
.alert-item.critical { background: rgba(244, 67, 54, 0.1); border-color: #f44336; }
.alert-icon { font-size: 28px; }
.alert-content { flex: 1; }
.alert-title { font-size: 15px; font-weight: 700; color: var(--color-text-primary); margin-bottom: 5px; }
.alert-message { font-size: 13px; color: var(--color-text-secondary); }
.alert-time { font-size: 12px; color: var(--color-text-secondary); white-space: nowrap; }
.empty-state { text-align: center; padding: 80px 20px; }
.empty-icon { font-size: 80px; margin-bottom: 20px; opacity: 0.5; }
.empty-text { color: var(--color-text-secondary); font-size: 16px; }
@media (max-width: 768px) {
  .host-selector, .time-range-selector, .metric-selector { flex-direction: column; }
  .chart-content { height: 300px; }
  .prediction-cards { grid-template-columns: 1fr; }
}
</style>
